from conan import ConanFile
from conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout
from conan.tools.files import apply_conandata_patches, copy, export_conandata_patches, get, replace_in_file, rm, rmdir, rename
from conan.tools.microsoft import is_msvc
import os

class LFSConan(ConanFile):
    name = "lfs"
    description = "lua file system"
    license = "MIT license"
    url = "https://github.com/conan-io/conan-center-index"
    homepage = "https://github.com/lunarmodules/luafilesystem.git"
    topics = ("lua", "file management")
    package_type = "library"
    settings = "os", "arch", "compiler", "build_type"
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
    }
    default_options = {
        "shared": False,
        "fPIC": True,
    }
    
    def export_sources(self):
        copy(self, "CMakeLists.txt", self.recipe_folder, self.export_sources_folder)
        export_conandata_patches(self)

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC

    def configure(self):
        if self.options.shared:
            self.options.rm_safe("fPIC")
            
    def requirements(self):
        self.requires("luajit/2.1.0-beta3")

    def layout(self):
        cmake_layout(self, src_folder=".")

    def source(self):
        get(self, **self.conan_data["sources"][self.version],
            destination=self.source_folder, strip_root=True)

    def generate(self):
        tc = CMakeToolchain(self)
        tc.generate()
        deps = CMakeDeps(self)
        deps.generate()
              
    def _patch_sources(self):
        apply_conandata_patches(self)
        # remove bundled xxhash
        if self.version == "1.7.0.2":
            replace_in_file(self, os.path.join(self.source_folder, "src", "lfs.c"), "#define LFS_VERSION \"1.7.0\"", "#define LFS_VERSION \"1.7.0.2\"")
        
        if self.version == "1.7.0":
            replace_in_file(self, os.path.join(self.source_folder, "src", "lfs.c"), "#define LFS_VERSION \"1.6.3\"", "#define LFS_VERSION \"1.7.0\"")

    def build(self):
        self._patch_sources()  # It can be apply_conandata_patches(self) only in case no more patches are needed
        cmake = CMake(self)
        cmake.configure()
        cmake.build()

    def package(self):
        copy(self, "LICENSE", src=self.source_folder, dst=os.path.join(self.package_folder, "licenses"))
        cmake = CMake(self)
        cmake.install()

    def package_info(self):
        self.cpp_info.set_property("cmake_find_mode", "both")
        self.cpp_info.set_property("cmake_file_name", "LFS")
        self.cpp_info.set_property("cmake_target_name", "LFS::LFS")
        self.cpp_info.libs = ["lfs"]
